<template>
  <div>
    <el-card class="update-log">
      <el-form
        :rules="rules"
        :style="{ background: '#fff' }"
        class="hang"
        ref="form"
        :model="form"
        label-width="380px"
        v-loading="loading"
        element-loading-text="加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-row>
          <el-col :span="20">
            <el-form-item label="标题" prop="title">
              <el-input
                maxlength="20"
                v-model="form.title"
                placeholder="请输入工单标题"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="紧急程度" prop="urgencyLevel">
              <el-radio-group v-model="form.urgencyLevel">
                <el-radio label="0">问题咨询</el-radio>
                <el-radio label="1">报障</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="手机号码" prop="mobile">
              <el-input
                v-model="form.mobile"
                placeholder="请输入手机号码"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="问题描述" prop="des">
              <quill-editor
                ref="myQuillEditor"
                v-model="form.des"
                :style="{ height: '300px', marginBottom: '60px' }"
                :options="editorOption"
                @change="changeQuillEditor"
              >
              </quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="17">
            <el-form-item label="附件">
              <el-upload
                style="width: 400px"
                class="upload-demo"
                multiple
                action="#"
                v-loading="huanchong"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :file-list="goodsList"
                :http-request="uploadFile"
                accept=".txt,.jpg,.png,.pdf,.doc,.mp4"
                :limit="5"
                :on-exceed="handleExceed"
                :before-upload="checkFileType"
              >
                <el-button size="small">点击上传</el-button>
                <span slot="tip" class="el-upload__tip" style="color: red">
                  (可以支持.txt、.jpg、.png、.pdf、.doc、.mp4等类型，附件上传不可超过5个且单个附件不超过8M)
                </span>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15" :style="{ textAlign: 'right' }">
            <el-button @click="reset">重 置</el-button>
            <el-button type="primary" @click="submit">提 交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import { getQnToken } from "@/api/system/user";
import * as qiniu from "qiniu-js";
import { addData } from "@/api/system/order/index";
export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      loading:false,
      // 显示缓冲状态
      huanchong: false,
      type: 0,
      radio: "1",
      form: {},
      content: "",
      editorOption: {
         modules: {
          toolbar: [
            // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
            ["bold", "italic", "underline", "strike"], // 引用  代码块-----['blockquote', 'code-block']
            ["blockquote", "code-block"], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
            [{ header: 1 }, { header: 2 }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
            [{ list: "ordered" }, { list: "bullet" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
            [{ script: "sub" }, { script: "super" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
            [{ indent: "-1" }, { indent: "+1" }], // 文本方向-----[{'direction': 'rtl'}]
            [{ direction: "rtl" }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
            [{ size: ["small", false, "large", "huge"] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
            [{ color: [] }, { background: [] }], // 字体种类-----[{ font: [] }]
            [{ font: [] }], // 对齐方式-----[{ align: [] }]
            [{ align: [] }], // 清除文本格式-----['clean']
            ["clean"], // 链接、图片、视频-----['link', 'image', 'video']
            // ["image"],
          ],
        },
      },
      // 表单校验
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        des: [{ required: true, message: "问题描述不能为空", trigger: "blur" }],

        urgencyLevel: [{ required: true, message: "紧急程度为必选项", trigger: "blur" }],
        mobile: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      goodsList: [],
      // 存储七牛云token
      qnData: {},
      goodsIn: "",
      imgIn: "",
    };
  },
  methods: {
    /** 获取七牛云token */
    getQnToken() {
      return new Promise((resolve, reject) => {
        getQnToken().then((response) => {
          resolve(response);
        });
      });
    },
    async uploadFile(uploadInfo) {
      let response = await this.getQnToken();
      if (response.code == 200) {
        this.qnData.token = response.data.token;
        let config = {
          useCdnDomain: true,
          region: qiniu.region.z0,
        };
        let putExtra = {
          fname: "",
          params: {},
          mimeType: null,
        };
        var observable = qiniu.upload(
          uploadInfo.file,
          response.data.qiniuKey,
          this.qnData.token,
          putExtra,
          config
        );
        observable.subscribe({
          next: (res) => {
            if (res.total.percent != 100) {
              this.huanchong = true;
            } else {
              this.huanchong = false;
            }
          },
          complete: (result) => {
            let avatar = `http://img.mofankj.com/${result.key}`;
            let data = {
              avatar,
            };
            this.goodsList.push({
              name: uploadInfo.file.name,
              url: data.avatar,
              urlName: result.key,
            });
          },
        });
      }
    },

    submit() {
      this.loading = true;
      let list = [];
      let imgList = [];
      for (let i = 0; i < this.goodsList.length; i++) {
        list.push(this.goodsList[i].urlName);
        imgList.push(this.goodsList[i].name);
        this.goodsIn = list + "";
        this.imgIn = imgList + "";
      }
      this.$refs["form"].validate((valid) => {
        let obj = this.$refs.myQuillEditor.quill;
        let params = {
          title: this.form.title,
          // des: obj.root.innerText,
          des:this.content,
          urgencyLevel: Number(this.form.urgencyLevel),
          mobile: this.form.mobile,
          email: this.form.email,
          attachUrl: this.goodsIn,
          attachName: this.imgIn,
        };
        addData(params).then((res) => {
          if (res.code == 200) {
            this.loading = false;
            this.$message.success("工单创建成功！");
            this.$router.push("/order/profile");
          } else {
            this.$message.error(`${res.msg}`);
          }
        });
      });
    },
    reset() {
      this.form = {};
    },
    changeQuillEditor(value) {
      this.content = value.html;
    },
    // 限制上传文件大小
    checkFileType(file) {
      console.log("file", file);
      // 1KB=1024B   1MB=1024KB   1GB=1024MB
      let fileSize = file.size / 1024 / 1024;
      console.log(fileSize);
      if (fileSize > 8) {
        this.$message.error("上传文件不能超过8M!");
        this.goodsList = [];
        return false;
      }
    },
    // 移除文件时的提示
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 上传文件超过指定个数时的提示信息
    // 文件超限时的提示
    handleExceed(files, goodsList) {
      this.$message.warning(`当前限制选择 5 个文件`);
    },
    // 移除文件
    handleRemove(file) {
      console.log("移除文件", file);
      // 上传
      /* this.goodsList.forEach((value, index, array) => {
        if (file.url == value.url) {
          array.splice(index, 1);
          this.goodsIn = [];
          this.countSum = 0;
        }
      }); */
    },
  },
};
</script>

<style lang="scss" scoped>
.ql-container {
  height: 380px;
}
.el-upload__tip {
  width: 551px;
  display: inline-block;
  /* background-color: pink; */
}
</style>
